package zy.blue7.doscan;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author blue7
 * @version 1.0
 * @date 2021/7/26 15:40
 */
public class ZYImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar , ResourceLoaderAware, BeanFactoryAware {

	private ResourceLoader resourceLoader;

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader=resourceLoader;
	}

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		ZYClassPathBeanDefinitionScanner classPathBeanDefinitionScanner=new ZYClassPathBeanDefinitionScanner(registry,false);
		classPathBeanDefinitionScanner.setResourceLoader(resourceLoader);
		classPathBeanDefinitionScanner.resetFilters();

		MultiValueMap<String, Object> allAnnotationAttributes = importingClassMetadata.getAllAnnotationAttributes("org.springframework.context.annotation.ComponentScan");
		List<Object> basePackages = allAnnotationAttributes.get("basePackages");

		List<String> collect=new ArrayList<>();

		basePackages.forEach(basePackage->{
			List<String> list = Arrays.asList((String[]) basePackage);
			collect.addAll(list);
		});
		/**
		 * todo 这里扫描的包可以通过 AnnotationMetadata 来获取
		 * AnnotationMetadata 是配置类上所有注解信息， todo 有两种方法， 1 直接使用compant扫描的包，2 或者自己自定义一个注解，该注解中设置要扫描的包路径
		 */
		classPathBeanDefinitionScanner.doScan(collect.toArray(new String[collect.size()]));
		System.out.println("===================");
//		classPathBeanDefinitionScanner.doScan("zy.blue7");

	}
}
